package caidan.net;

import caidan.MainApp;
import caidan.res.Resource;
import jinyilw.swing.SystemTools;
import jinyilw.common.TextTools;
import jinyilw.common.database.JdbcTools;
import jinyilw.swing.FontTools;
import jinyilw.swing.SwingTools;
import jinyilw.swing.visuals.Jcomp.JActImageComp;
import jinyilw.swing.visuals.Rcomp.ROptionPane;
import jinyilw.swing.visuals.border.RTitledBorder;
import jinyilw.swing.visuals.border.RichTitleBorder;
import jinyilw.swing.visuals.comp.RoundIconButton;
import jinyilw.swing.visuals.layout.VEFlowLayout;
import jinyilw.swing.visuals.text.WrapLabel;
import jinyilw.swing.visuals.window.HintWindow;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public abstract class AbstractSuggestPanel extends JPanel
{
	private static final long serialVersionUID = -2316540759281972733L;
	private static final int suggestWidth = 200;
	private static final Font suggestFont = FontTools.getSystemFont(13);

	protected JPanel contentPanel, bottomPanel;
	protected JButton sendButton;
	protected ArrayList<SuggestLabel> suggestLabels;
	protected JdbcTools jdbcTools;
	protected boolean isConnected;

	public AbstractSuggestPanel()
	{
		super(new BorderLayout());
		init();
	}
	private void init()
	{
		// initNet();
		createGUI();
		initLayout();
		initListeners();
		suggestLabels = new ArrayList<SuggestLabel>();
	}
	public void initNet()
	{
	}

	private void createGUI()
	{
		contentPanel = new JPanel();
		bottomPanel = new JPanel();
		sendButton = new JButton("添加意见建议", Resource.addIcon);
		// freshButton = new JButton("刷新或重连网络", Resource.freshIcon);
		setBorder(new RTitledBorder("伙食建议", TitledBorder.CENTER,
				TitledBorder.BELOW_TOP, FontTools.getCustomFont(18),
				Color.cyan));
	}

	private void initLayout()
	{
		// setLayout(new BorderLayout());
		contentPanel.setLayout(new VEFlowLayout());
		add(new JScrollPane(contentPanel), BorderLayout.CENTER);
		add(bottomPanel, BorderLayout.SOUTH);
		bottomPanel.add(sendButton);
		// bottomPanel.add(freshButton);
	}

	private void initListeners()
	{
		sendButton.addActionListener((ActionEvent e) ->
		{
			showSuggestDialog();
		});
	}

	private final String[] options = {"确定并发送", "确定", "取消",};
	private Object[] suggestDialogObjects;
	private JTextField userTextField;
	private JTextArea contenTextArea;
	private int optionResult = -1;
	private void showSuggestDialog()
	{
		if (suggestDialogObjects == null)
		{
			suggestDialogObjects = new Object[4];
			suggestDialogObjects[0] = "输入您的用户名：";
			suggestDialogObjects[1] = userTextField = new JTextField(20);
			userTextField.setText(MainApp.getUserName());
			suggestDialogObjects[2] = "\n输入您的意见建议：";
			suggestDialogObjects[3] = contenTextArea = new JTextArea(10, 20);
			contenTextArea.setLineWrap(true);
			contenTextArea.setFont(FontTools.defaultFont);
		}
		if (optionResult != -1)
		{
			contenTextArea.setText("");
		}
		optionResult = ROptionPane.showOptionDialog(this, suggestDialogObjects,
				"添加意见建议", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
				Resource.suggestIcon, options, null);
		if (optionResult == 0 || optionResult == 1)
		{
			String user = userTextField.getText();
			String content = contenTextArea.getText();
			if (TextTools.isBlank(user) || TextTools.isBlank(content))
			{
				ROptionPane.showMessageDialog(this, "信息不完整，请输入完整信息！");
				optionResult = -1;
				showSuggestDialog();
			} else if (content.length() < 10)
			{
				ROptionPane.showMessageDialog(this, "最少输入10个字，请重新输入！");
				optionResult = -1;
				showSuggestDialog();
			} else
			{
				Suggest suggest = new Suggest(user, content, new Date());
				SuggestLabel label = new SuggestLabel(suggest);
				addSuggestLabel(label);
				if (optionResult == 0)
					sendSuggest(label);
			}
		}
	}

	// protected boolean isFristOpen = true;
	public abstract void reloadDatabase();

	protected void readFromDatabase()
	{
		if (!isConnected)
			return;
		List<Suggest> suggestList = null;
		try
		{
			suggestList = jdbcTools.findMoreRefResult("select * from suggest",
					Suggest.class);
		} catch (Exception e)
		{
			e.printStackTrace();
			return;
		}

		int i = 0, size = suggestLabels.size();
		SuggestLabel label;
		if (suggestList != null)
			for (Suggest suggest : suggestList)
			{
				if (i < size)
				{
					label = suggestLabels.get(i);
					label.setLabel(suggest, true, false);
				} else
				{
					label = new SuggestLabel(suggest, true);
					suggestLabels.add(label);
				}
				i++;
			}
		if (i < size)
			for (int j = size - 1; j >= i; j--)
				suggestLabels.remove(j);
	}

	public abstract void removeSuggestLabel(SuggestLabel label);

	public abstract void addSuggestLabel(SuggestLabel label);

	public abstract boolean isClient();

	public abstract void sendSuggest(SuggestLabel suggestLabel);

	// public abstract boolean isConnected();

	class SuggestLabel extends WrapLabel
	{
		private static final long serialVersionUID = 6135927525395642839L;
		Suggest suggest;
		boolean isNet;
		boolean isSend;
		JActImageComp sendComp;
		private final RichTitleBorder titleBorder = new RichTitleBorder(null,
				FontTools.defaultFont);
		private final RoundIconButton closeButton = new RoundIconButton(
				Resource.closeIcon);
		private final JActImageComp copyComp = new JActImageComp(Resource.copyIcon);

		public SuggestLabel(Suggest suggest)
		{
			this(suggest, false);
		}

		public SuggestLabel(Suggest suggest, boolean isNet)
		{
			this(suggest, isNet, false);
		}

		public SuggestLabel(Suggest suggest, boolean isNet, boolean isSend)
		{
			setWrapWidth(suggestWidth);
			setFont(suggestFont);
			setBorder(titleBorder);
			closeButton.addClickOperator((Object o) ->
			{
				removeSuggestLabel(this);
			});
			copyComp.setToolTipText("复制到剪贴板");
			copyComp.addClickOperater((Object o) ->
			{
				if (SystemTools.setSysClipboardText(suggest.getContent()))
					HintWindow.showHint("已复制到剪贴板", SuggestLabel.this);
			});
			SwingTools.addTitleComponents(this, closeButton, copyComp);
			setLabel(suggest, isNet, isSend);
		}

		public void setLabel(Suggest suggest, boolean isNet, boolean isSend)
		{
			this.suggest = suggest;
			this.isNet = isNet;
			this.isSend = isSend;
			updateTitle();
			setText("      " + suggest.getContent());
			if (isNet)
			{
				if (sendComp != null)
					remove(sendComp);
			} else
			{
				if (sendComp == null)
				{
					sendComp = new JActImageComp(Resource.sendIcon);
					sendComp.addClickOperater((Object o) ->
					{
						sendSuggest(this);
					});
				}
				SwingTools.addTitleComponents(this, sendComp);
				if (isSend)
				{
					sendComp.setToolTipText("已发送");
					sendComp.setEnabled(false);
				} else
				{
					sendComp.setToolTipText("发送到网络");
					sendComp.setEnabled(true);
				}
			}
		}

		public void updateTitle()
		{
			String title = suggest.getTitle();
			if (isClient())
			{
				if (isNet)
				{
					title += "-网络";
					if (!isConnected)
						title += "(缓存)";
				} else
					title += "-本地";
			} else
				title += isNet ? "-已推送" : "-未推送";
			titleBorder.setTitle(title);
		}

		public void writeData(DataOutputStream dos)
		{
			try
			{
				dos.writeBoolean(isNet);
				dos.writeBoolean(isSend);
				dos.writeUTF(suggest.getUser());
				dos.writeUTF(suggest.getContent());
				dos.writeUTF(suggest.getDateString());
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		@Override
		public Dimension getPreferredSize()
		{
			Dimension dim = super.getPreferredSize();
			if (dim.width < suggestWidth - 5)
				dim.width = suggestWidth - 5;
			return dim;
		}
	}
}
